package com.learn.javase.chapter18.classloader.urlclassloader;

import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

/**
 * @author wsh
 * @date 2022-05-11 00:28
 */
public class URLClassLoaderTest {
    private static Connection conn;

    /**
     * 获取数据库连接
     * 通过这种方式来获取数据库连接，可无须将MySQL驱动添加到classpath环境变量中。
     *
     * @param url
     * @param user
     * @param pass
     * @return
     * @throws Exception
     */
    public static Connection getConn(String url, String user, String pass) throws Exception {
        if (conn == null) {
            // 创建一个URL数组
            URL[] urls = {new URL("file:/Users/apple/workspaces/idea/study/learn-javase/src/main/java/com/learn/javase/chapter18/classloader/urlclassloader/mysql-connector-java-5.1.30-bin.jar")};//从本地文件系统加载
            //URL[] urls = {new URL("http:www***")};//从网络上用HTTP协议访问来加载
            //URL[] urls = {new URL("ftp:/Users")};//从网络上用FTP协议访问来加载

            // 以默认的ClassLoader作为父ClassLoader，创建URLClassLoader
            URLClassLoader urlClassLoader = new URLClassLoader(urls);
            // 加载MySQL的JDBC驱动，并创建默认实例
            Driver driver = (Driver) urlClassLoader.loadClass("com.mysql.jdbc.Driver").newInstance();
            // 创建一个设置JDBC连接属性的Properties对象
            Properties props = new Properties();
            // 至少需要为该对象传入user和password两个属性
            props.setProperty("user", user);
            props.setProperty("password", pass);
            // 调用Driver对象的connect方法来取得数据库连接
            conn = driver.connect(url, props);
        }
        return conn;
    }

    public static void main(String[] args) {
        try {
            Connection conn = getConn("jdbc:mysql://localhost:3306/mysql", "root", "root");
            System.out.println("获取数据库连接：成功");
        } catch (Exception e) {
            System.out.println("获取数据库连接：失败");
            e.printStackTrace();
        }
    }
}
